package com.ww.springboot.boot.redisson.ratelimiter;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;

import com.ww.springboot.boot.redisson.BladeExpressionEvaluator;
import jodd.util.StringUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.expression.AnnotatedElementKey;
import org.springframework.expression.EvaluationContext;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

@Aspect
public class RedisRateLimiterAspect implements ApplicationContextAware {
    private final BladeExpressionEvaluator evaluator = new BladeExpressionEvaluator();
    private final RedisRateLimiterClient rateLimiterClient;
    private ApplicationContext applicationContext;

    @Around("@annotation(limiter)")
    public Object aroundRateLimiter(ProceedingJoinPoint point, RateLimiter limiter) throws Throwable {
        String limitKey = limiter.value();
        Assert.hasText(limitKey, "@RateLimiter value must have length; it must not be null or empty");
        String limitParam = limiter.param();
        String rateKey;
        if (StringUtil.isNotBlank(limitParam)) {
            String evalAsText = this.evalLimitParam(point, limitParam);
            rateKey = limitKey + ':' + evalAsText;
        } else {
            rateKey = limitKey;
        }

        long max = limiter.max();
        long ttl = limiter.ttl();
        TimeUnit timeUnit = limiter.timeUnit();
        RedisRateLimiterClient var10000 = this.rateLimiterClient;
        point.getClass();
        return var10000.allow(rateKey, max, ttl, timeUnit, point::proceed);
    }

    private String evalLimitParam(ProceedingJoinPoint point, String limitParam) {
        MethodSignature ms = (MethodSignature) point.getSignature();
        Method method = ms.getMethod();
        Object[] args = point.getArgs();
        Object target = point.getTarget();
        Class<?> targetClass = target.getClass();
        EvaluationContext context = this.evaluator.createContext(method, args, target, targetClass, this.applicationContext);
        AnnotatedElementKey elementKey = new AnnotatedElementKey(method, targetClass);
        return this.evaluator.evalAsText(limitParam, elementKey, context);
    }

    public void setApplicationContext(@NonNull ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    public RedisRateLimiterAspect(final RedisRateLimiterClient rateLimiterClient) {
        this.rateLimiterClient = rateLimiterClient;
    }
}